package com.faith.dynamic.bean;
import com.faith.dynamic.enums.FaithSysExceptionEnum;
import com.faith.dynamic.exception.FaithSysException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName BaseController$
 * @Description 异常拦截
 * @Author faith$
 * @Date 2019/7/25 15:00
 * @Version 1.0
 **/
@Controller
@ControllerAdvice
public class BaseController {

    public BaseController() {
    }

    protected <T> BaseResponseObj<T> success(T dataObject) {
        return new BaseResponseObj(dataObject);
    }

    protected BaseResponseObj success() {
        return new BaseResponseObj();
    }

    @ExceptionHandler
    @ResponseBody
    public BaseResponseObj exceptionHandler(HttpServletRequest request, HttpServletResponse httpResponse, Exception ex) {
        BaseResponseObj BaseResponseObj = new BaseResponseObj();
        ex.printStackTrace();

        try {
            if (ex instanceof FaithSysException) {
                FaithSysException FaithSysException = (FaithSysException)ex;
                BaseResponseObj.setMessage(FaithSysException.getMessage());
                BaseResponseObj.setCode(FaithSysException.getCode());
                return BaseResponseObj;
            } else if (ex instanceof MethodArgumentNotValidException) {
                BaseResponseObj.setCode(FaithSysExceptionEnum.ILLEGAL_PARAM.getCode());
                String message = ex.getMessage();
                int start = message.lastIndexOf("default message");
                message = message.substring(start, message.length()).replace("default message", "").replace("]]", "]");
                BaseResponseObj.setMessage(FaithSysExceptionEnum.ILLEGAL_PARAM.getMessage() + message);
                return BaseResponseObj;
            } else {
                BaseResponseObj.setMessage(FaithSysExceptionEnum.INTERNAL_ERROR.getMessage());
                BaseResponseObj.setCode(FaithSysExceptionEnum.INTERNAL_ERROR.getCode());
                return BaseResponseObj;
            }
        } catch (Exception var8) {
            BaseResponseObj.setMessage(FaithSysExceptionEnum.INTERNAL_ERROR.getCode());
            BaseResponseObj.setCode(FaithSysExceptionEnum.INTERNAL_ERROR.getMessage());
            return BaseResponseObj;
        }
    }

}
